package com.alibaba.cloud.utils;


import org.apache.commons.lang3.StringUtils;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;


/**
 * The Class CookieUtil.
 *
 * @ClassName: CookieUtil
 * @author: zhb1316783262@163.com
 * @date: 2018年11月24日 下午7:02:41
 * @Description: 
 */
public class CookieUtil {
	
	/** The Constant COOKIE_DOMAIN. */
	private final static String COOKIE_DOMAIN = "localhost";

	/** The Constant COOKIE_NAME. */
	private final static String COOKIE_NAME = "seckill_login_token";

	/**
	 * Read login token.
	 *
	 * @param request the request
	 * @return the string
	 */
	public static String readLoginToken(HttpServletRequest request) {
		Cookie[] cks = request.getCookies();
		if (cks != null) {
			for (Cookie ck : cks) {
				if (StringUtils.equals(ck.getName(), COOKIE_NAME)) {
					return ck.getValue();
				}
			}
		}
		return null;
	}

	/**
	 * Write login token.
	 *
	 * @param response the response
	 * @param token the token
	 */
	public static void writeLoginToken(HttpServletResponse response, String token) {
		Cookie ck = new Cookie(COOKIE_NAME, token);
		ck.setDomain(COOKIE_DOMAIN);
		ck.setPath("/");// 代表设置在根目录
		ck.setHttpOnly(true);
		// 单位是秒。
		// 如果这个maxage不设置的话，cookie就不会写入硬盘，而是写在内存。只在当前页面有效。
		ck.setMaxAge(60 * 60 * 24 * 365);// 如果是-1，代表永久
		// log.info("write cookieName:{},cookieValue:{}", ck.getName(), ck.getValue());
		response.addCookie(ck);
	}

	/**
	 * Del login token.
	 *
	 * @param request the request
	 * @param response the response
	 */
	public static void delLoginToken(HttpServletRequest request, HttpServletResponse response) {
		Cookie[] cks = request.getCookies();
		if (cks != null) {
			for (Cookie ck : cks) {
				if (StringUtils.equals(ck.getName(), COOKIE_NAME)) {
					ck.setDomain(COOKIE_DOMAIN);
					ck.setPath("/");
					ck.setMaxAge(0);// 设置成0，代表删除此cookie。
					response.addCookie(ck);
					return;
				}
			}
		}
	}
}
